---
title: 'API Reference: ApolloServer'
api_reference: true
---

This article documents the `ApolloServer` class from the `@apollo/server` package. You can use the `ApolloServer` class to create an instance of Apollo Server that you can then pass to a web framework integration function (e.g., `startStandaloneServer` or `expressMiddleware`).

> Check out our [Getting Started](../getting-started) guide for an example of setting up Apollo Server!

## `constructor`

Returns an initialized `ApolloServer` instance.

Takes an `options` object as a parameter. Supported fields of this object are described below.

### Example

<MultiCodeBlock>

```ts
import { ApolloServer } from '@apollo/server';

const server = new ApolloServer({
  typeDefs,
  resolvers,
});
```

</MultiCodeBlock>

### Options

<table class="field-table">
  <thead>
    <tr>
      <th>Name /<br/>Type</th>
      <th>Description</th>
    </tr>
  </thead>

<tbody>
<tr>
<td colspan="2">

**Specifying a schema**

</td>
</tr>
<tr class="required">
<td>

###### `typeDefs`

`string`, `DocumentNode`, or `Array<DocumentNode>`

</td>
<td>

A valid [Schema Definition Language](../schema/schema/#the-schema-definition-language) (SDL) string, document, or documents that represent your server's GraphQL schema. To generate documents, you can apply the `gql` tag (from [`graphql-tag`](https://www.npmjs.com/package/graphql-tag)) to valid SDL strings.

**Required** unless you provide a [`schema`](#schema) or a [`gateway`](#gateway).

For an example, see [Define your GraphQL schema](../getting-started/#step-3-define-your-graphql-schema).

</td>
</tr>

<tr class="required">
<td>

###### `resolvers`

`Object` or `Array`

</td>
<td>

A map of functions that populate data for individual schema fields. Can also be an array of multiple maps that are merged.

While technically optional, if you are providing `typeDefs`, it is strongly recommended that you provide `resolvers` as well.

For details, see [Resolvers](../data/resolvers/).

</td>
</tr>

<tr>
<td>

###### `schema`

`Object`

</td>

<td>

An executable GraphQL schema. Under the hood, Apollo Server automatically generates this field from [`typeDefs`](#typedefs) and [`resolvers`](#resolvers).

This field is helpful if:

- You are [building a subgraph for Apollo Federation](../using-federation/apollo-subgraph-setup), which uses the `buildSubgraphSchema` function to generate its schema
- You are using a function like `makeExecutableSchema` from [`graphql-tools`](https://www.graphql-tools.com/docs/generate-schema) to create your schema
- You are using a library that takes a code-first approach (i.e., instead of a schema-first approach) to generate a schema

</td>
</tr>

<tr>
<td>

###### `gateway`

`Object`

</td>

<td>

You can use this field to integrate your server with [Apollo Gateway](../using-federation/api/apollo-gateway/).

</td>
</tr>

<tr>
<td colspan="2">

**Schema options**

</td>
</tr>

<tr>
<td>

###### `introspection`

`boolean`

</td>

<td>

If `true`, enables [schema introspection](https://graphql.org/learn/introspection/) by clients. This is required to use tools that figure out your server's schema from talking to it directly, like Apollo Sandbox and GraphQL Playground. (It's not needed for the non-Sandbox version of Apollo Studio Explorer, which uses the schema published in the Studio schema registry instead.)

The default value is `true`, **unless** the `NODE_ENV` environment variable is set to `production`.

</td>
</tr>

<tr>
<td>

###### `maxRecursiveSelections`

`boolean` or `number`

</td>

<td>

If `true`, enables a validation rule that computes how many selections would be in the operation if its named fragment definitions were recursively inlined (without actually inlining) and errors if the count exceeds 10,000,000. If `number`, it instead errors if the count exceeds this number.

This rule is executed before any provided `validationRules`, and can be useful to avoid performance issues with those rules or any downstream plugins.

The default value is `false`.

</td>
</tr>

<tr>
<td>

###### `hideSchemaDetailsFromClientErrors`

`boolean`

</td>

<td>

If `true`, Apollo Server strips out "did you mean" suggestions when an operation fails validation.

For example, with this option set to `true`, an error would read `Cannot query field "help" on type "Query".`. With this option set to `false`, the same error would read `Cannot query field "help" on type "Query". Did you mean "hello"?`.

The default value is `false`, but Apollo recommends enabling this option in production to avoid leaking information about your schema.

</td>
</tr>

<tr>

<td>

###### `fieldResolver`

`GraphQLFieldResolver`

</td>

<td>

A custom resolver that will replace Apollo Server's [default field resolvers](../data/resolvers/#default-resolvers).

</td>
</tr>

<tr>
<td>

###### `rootValue`

`Any` or `Function`

</td>
<td>

A value or function called with the parsed `Document`, creating the root value passed to the GraphQL executor.

Providing a function is useful if you want to use a different root value depending on the operation's details, such as whether it's a query or mutation.

</td>
</tr>

<tr>
<td>

###### `validationRules`

`Array<Function>`

</td>
<td>

An array containing custom functions to use as additional [validation rules](https://github.com/graphql/graphql-js/tree/master/src/validation/rules) when validating operations against the schema. Note that these rules should depend only on the operation and the schema, not on anything else specific to an individual request, as the result of successful validation is cached across requests.

</td>
</tr>

<tr>
<td>

###### `documentStore`

`KeyValueCache<DocumentNode>` or `null`

</td>
<td>

A key-value cache that Apollo Server uses to store previously encountered GraphQL operations (as `DocumentNode`s). It does _not_ store query _results_.

Whenever Apollo Server receives an incoming operation, it checks whether that exact operation is present in its `documentStore`. If it's present, Apollo Server can safely skip parsing and validating the operation, thereby improving performance.

The default `documentStore` is an [`InMemoryLRUCache`](https://github.com/apollographql/apollo-utils/blob/main/packages/keyValueCache/src/InMemoryLRUCache.ts) with an approximate size of 30MiB. This is usually sufficient unless the server processes a large number of unique operations. Provide this option if you want to change the cache size or store the cache information in an alternate location.

To use `InMemoryLRUCache` but change its size to an amount `approximateDocumentStoreMiB`:

<div style="max-width: 400px;">

```typescript
import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache';
import type { DocumentNode } from 'graphql';

new ApolloServer({
  documentStore: new InMemoryLRUCache<DocumentNode>({
    maxSize: Math.pow(2, 20) * approximateDocumentStoreMiB,
    sizeCalculation: InMemoryLRUCache.sizeCalculation,
  }),
  // ...
});
```

</div>

Pass `null` to disable this cache entirely.

</td>
</tr>

<tr>
<td colspan="2">

**Protocol options**

</td>
</tr>

<tr>
<td>

###### `persistedQueries`

`Object` or `false`

</td>

<td>

If you're using [automated persisted queries (APQ)](../performance/apq/), you can provide an object with `cache` and/or `ttl` fields to customize how Apollo Server stores the mapping between operation hashes and query strings, or provide `false` to disable APQ entirely.

</td>
</tr>

<tr>
<td>

###### `csrfPrevention`

`boolean` or `Object`

</td>
<td>

By default, the [CSRF prevention](../security/cors#preventing-cross-site-request-forgery-csrf) feature is enabled to protect Apollo Server from CSRF and XS-Search attacks.

This feature can prevent certain `GET` requests from executing GraphQL operations if those requests don't specify [certain headers](../security/cors/#why-use-cors). You can configure the headers that allow operation execution by passing a configuration object to this option (e.g., `csrfPrevention: { requestHeaders: ['special-header'] }`).

If your server has clients that send `GET` requests and those clients **aren't** one of Apollo's client libraries (Web, iOS, Kotlin), you might need to modify the configuration of those clients to use this feature. For more details, see [the CSRF prevention documentation](../security/cors#preventing-cross-site-request-forgery-csrf).

You can disable this recommended security feature by passing `false` to `csrfPrevention`.

</td>
</tr>

<tr>
<td>

###### `formatError`

`Function`

</td>
<td>

Provide this function to transform the structure of error objects before they're sent to a client.

The `formatError` hook receives two arguments: the first is a [`GraphQLFormattedError`](https://github.com/graphql/graphql-js/blob/29bf39faa670effd3c1561a1512ec7767658a63b/src/error/GraphQLError.ts#L215) (to be sent with the response), and the second is the original error [(wrapped in GraphQLError if thrown by a resolver)](../data/errors/#for-client-responses). This function should return a [`GraphQLFormattedError`](https://github.com/graphql/graphql-js/blob/29bf39faa670effd3c1561a1512ec7767658a63b/src/error/GraphQLError.ts#L215) object.

</td>
</tr>

<tr>
<td>

###### `apollo`

`Object`

</td>
<td>

An object containing configuration options for connecting Apollo Server to [Apollo Studio](https://www.apollographql.com/docs/studio/). Each field of this object can also be set with an environment variable, which is the recommended method of setting these parameters. All fields are optional. The fields are:

- `key`: The [graph API key](https://www.apollographql.com/docs/studio/api-keys/#graph-api-keys) that Apollo Server should use to authenticate with Apollo Studio. You can set this with the `APOLLO_KEY` environment variable.
- `graphRef`: A reference of your graph in Apollo's registry, such as `graph-id@my-variant` or just `graph-id`. You can set this with the `APOLLO_GRAPH_REF` environment variable.
- `graphId`: The ID of your graph in Apollo's registry. You can set this with the `APOLLO_GRAPH_ID` environment variable. You may not specify this if you specify the graph ref.
- `graphVariant`: The [variant](https://www.apollographql.com/docs/studio/schema/registry/#managing-environments-with-variants) of your graph to associate this server's schema and metrics with. You can set this with the `APOLLO_GRAPH_VARIANT` environment variable. The default value is `current`. You may not specify this if you specify the graph ref.

</td>
</tr>

<tr>
<td>

###### `allowBatchedHttpRequests`

`boolean`

</td>
<td>

Controls whether to allow [Batching Queries](../workflow/requests/#batching) in a single HTTP Request. Defaults to `false`. If a request comes in formatted as an array rather than as a single request object, an error will be thrown ( i.e., `Operation batching disabled`) _unless_ batching is enabled.

</td>
</tr>

<tr>
<td colspan="2">

**Lifecycle options**

</td>
</tr>

<tr>
<td>

###### `cache`

`KeyValueCache`

</td>
<td>

A [`KeyValueCache`](https://www.npmjs.com/package/@apollo/utils.keyvaluecache) which Apollo Server uses for several features, including APQs and full response caching. This cache is also available to Apollo Server's plugins.

The default cache is an [`InMemoryLRUCache`](https://www.npmjs.com/package/@apollo/utils.keyvaluecache) with a default size of roughly 30MiB. (For backwards-compatibility with Apollo Server 3, specifying `cache: 'bounded'` also selects this default bounded cache.)

To learn more about configuring Apollo Server's cache, see [Configuring cache backends](../performance/cache-backends).

</td>
</tr>

<tr>
<td>

###### `plugins`

`Array`

</td>
<td>

An array of [plugins](../integrations/plugins) to install in your server instance.

You can _also_ add plugins to your server before you start it using the [`addPlugin`](#addplugin) method. This might be useful in the event that your plugin needs to access the `ApolloServer` instance.

Apollo Server comes with several plugins that it installs automatically in their default configuration if certain conditions are met. For example, the usage reporting plugin is installed if you provide a graph API key and a graph ref. Apollo Server skips this automatic installation if you manually provide the plugin (in the `plugins` array or with the `addPlugin` method), or if you provide the plugin's corresponding "disabled" plugin (such as `ApolloServerPluginUsageReportingDisabled()` for `ApolloServerPluginUsageReporting`). For details, see the API references for these plugins: [usage reporting](./plugin/usage-reporting/), [schema reporting](./plugin/schema-reporting/), [landing page](./plugin/landing-pages/), [cache control](./plugin/cache-control/), and [inline trace](./plugin/inline-trace/).

</td>
</tr>

<tr>
<td>

###### `stopOnTerminationSignals`

`boolean`

</td>
<td>

By default, whenever Apollo Server receives a `SIGINT` or `SIGTERM` signal, it calls `await this.stop()` on itself. It then sends that same signal to itself to continue process shutdown. Subsequent `SIGINT` and `SIGTERM` signals are ignored while Apollo Server awaits `this.stop()`. Note that this does _not_ happen when `NODE_ENV` equals `test` or when Apollo Server is running in serverless mode.

Set this option to `false` to disable this default behavior, or to `true` to enable the behavior even when `NODE_ENV` _does_ equal `test`.

The signal handler is installed after [`start()`](#start) returns successfully.

You can also manually call `stop()` in other contexts. Note that `stop()` is asynchronous, so it isn't useful in a `process.on('exit')` handler.

</td>
</tr>

<tr>
<td colspan="2">

**Debugging options**

</td>
</tr>

<tr>
<td style="max-width: 200px;">

###### `includeStacktraceInErrorResponses`

`boolean`

</td>

<td>

If `true`, stack traces are included in GraphQL responses when errors occur.

Defaults to `true` unless the `NODE_ENV` environment variable is `production` or `test`.

</td>
</tr>

<tr>
<td>

###### `logger`

[`Logger`](https://www.npmjs.com/package/@apollo/utils.logger)

</td>
<td>

An object to use for logging in place of `console`. If provided, this object must implement all methods of [the `Logger` interface](https://www.npmjs.com/package/@apollo/utils.logger).

If you provide this value, Apollo Server automatically logs all messages of _all_ severity levels (`debug` through `error`). It is the responsibility of the logger to determine how to handle logged messages of each level.

This logger is automatically added to the `GraphQLRequestContext` object that's passed to all Apollo Server [plugin functions](../integrations/plugins/).

</td>
</tr>

<tr>
<td>

###### `parseOptions`

`Object`

</td>
<td>

An object that specifies how your server parses GraphQL operations. [See `graphql-js` for the available configuration options](https://github.com/graphql/graphql-js/blob/9df90799299f40b596938aba15e88c4cd4f2d376/src/language/parser.ts#L77).

</td>
</tr>

<tr>
<td>

###### `nodeEnv`

`string`

</td>
<td>

If this is set to any string value, use that value instead of the environment variable `NODE_ENV` for the features whose defaults depend on `NODE_ENV` (such as [`introspection`](#introspection)). Note that passing the empty string here is equivalent to running with the `NODE_ENV` environment variable unset. This is primarily meant for testing the effects of the `NODE_ENV` environment variable.

</td>
</tr>

<tr>
<td>

###### `status400ForVariableCoercionErrors`

`boolean`

</td>
<td>

> Note: Apollo Server v5 defaults this option to `true`. This option is deprecated in v5 and will be ignored in a future major version.

**Apollo Server v4 users should set this option to `true` (or better yet, upgrade to v5).** It mitigates a regression introduced in Apollo Server v4 where the server returns a 200 status code (instead of 400) when a client query provides invalid variables.

</td>
</tr>

<tr>
<td>

##### `dangerouslyDisableValidation`

`Boolean`
</td>
<td>
⚠️ Caution: this option can lead to security vulnerabilities and unexpected
behavior. Use of this option in production is not supported by Apollo.

When set to `true`, disable validation of graphql operations entirely.

You might find this option interesting for performance reasons if you handle
operation validation at build time and enforce that only known, validated
operations are allowed to be executed at runtime. Note that validation of
operations is cached in Apollo Server's document store.
</td>
</tr>

</tbody>
</table>

## `start`

The async `start` method instructs Apollo Server to prepare to handle incoming operations.

> Call `start` **only** if you are using a framework integration for a non-serverless environment (e.g., [`expressMiddleware`](./express-middleware)).
>
> - If you're using a serverless framework integration (such as Lambda), you **shouldn't** call this method before passing your server into the integration function. Your serverless integration function will take care of starting your server for you.
>
> - If you're using `startStandaloneServer` you do **not** need to start your server before [passing it directly to `startStandaloneServer`](./standalone).

Always call `await server.start()` _before_ passing your server into your integration function and starting to accept requests:

<MultiCodeBlock>

```ts
const server = new ApolloServer<MyContext>({
  typeDefs,
  resolvers,
});
await server.start();

app.use(
  '/graphql',
  cors<cors.CorsRequest>(),
  express.json(),
  expressMiddleware(server),
);
```

</MultiCodeBlock>

This allows you to react to Apollo Server startup failures by crashing your process instead of starting to serve traffic.

If you are testing your server using [`executeOperation`](../testing/testing/) (i.e., you're not actually starting an HTTP server), you don't need to call `start()` because `executeOperation` will do that for you.

### Triggered actions

The `start` method triggers the following actions:

1. If your server is a [federated gateway](https://www.apollographql.com/docs/federation/managed-federation/overview/), it attempts to fetch its schema. If the fetch fails, `start` throws an error.
2. Your server calls all of the [`serverWillStart` handlers](../integrations/plugins-event-reference/#serverwillstart) of your installed plugins. If any of these handlers throw an error, `start` throws an error.

## `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests`

**Serverless** integrations handle starting an Apollo Server instance in the background by calling the `startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests` method. This method is _synchronous_ and doesn't need to be `awaited`. This means any errors that occur happen in the background, so you can't immediately handle them. See [Building integrations](../integrations/building-integrations#ensure-successful-startup) for more details.

This method [triggers the same actions](#triggered-actions) as the `start()` method.

## `addPlugin`

You can use the `addPlugin` method to add plugins before your server is started. This is helpful when you want to add a plugin that accepts your initialized `ApolloServer` instance itself, like so:

<MultiCodeBlock>

```ts
const server = new ApolloServer({
  typeDefs,
  plugins: [makeFirstPlugin()],
});

server.addPlugin(makeSecondPlugin(server));
```

</MultiCodeBlock>

## `assertStarted`

Framework integrations should call `server.assertStarted()` to ensure a server has started before accepting requests. See [Building integrations](../integrations/building-integrations) for more details.

## `stop`

`ApolloServer.stop()` is an async method that tells all of Apollo Server's background tasks to complete. Specifically, it:

- Calls and awaits all [`drainServer` plugin handlers](../integrations/plugins-event-reference/#drainserver). These should generally:
  - Stop listening for new connections
  - Close idle connections (i.e., connections with no current HTTP request)
  - Close active connections whenever they become idle
  - Wait for all connections to be closed
  - After a grace period, if any connections remain active, forcefully close them. If you're using `startStandaloneServer`, this happens by default. Otherwise, you can use the [drain HTTP server plugin](./plugin/drain-http-server/) to drain your HTTP server.
- Transitions the server to a state where it will not start executing more GraphQL operations.
- Calls and awaits all [`serverWillStop` plugin handlers](../integrations/plugins-event-reference/#serverwillstop) (including the [usage reporting plugin](./plugin/usage-reporting/)'s handler, which sends a final usage report to Apollo Studio).
- If your server is a [federated gateway](https://www.apollographql.com/docs/federation/gateway/), `stop` also stops gateway-specific background activities, such as polling for updated service configuration.

This method takes no arguments. You should only call it after [`start()`](#start) returns successfully (or after you've called `startStandaloneServer` with your `ApolloServer` instance).

In some circumstances, Apollo Server calls `stop` automatically when the process receives a `SIGINT` or `SIGTERM` signal. See the [`stopOnTerminationSignals` constructor option](#stoponterminationsignals) for details.

## `executeOperation`

The async `executeOperation` method is used primarily for [testing GraphQL operations](../testing/testing/#testing-using-executeoperation) through Apollo Server's request pipeline _without_ sending an HTTP request.

```js
const response = await server.executeOperation({
  query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
  variables: { name: 'world' },
});
```

The `executeOperation` method takes two arguments:

- The first argument is an object describing the GraphQL operation to be executed.
  - Supported fields are listed in the table below.
- The second argument is the optional options object. This object includes the operation's optional [`contextValue`](../data/context#the-contextvalue-object). This argument is only optional if your server _doesn't_ expect a context value (i.e., your server uses the default context because you didn't explicitly provide another one).

```js
const response = await server.executeOperation({
  query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
  variables: { name: 'world' },
}, {
  contextValue: { userId: 'test' },
});
```

The `response` object returned from `executeOperation` is a `GraphQLResponse`, which has `body` and `http` fields.

Apollo Server 4 and 5 support incremental delivery directives such as `@defer` and `@stream` when combined with pre-release version `17.0.0-alpha.2` of `graphql-js`, and so the structure of `response.body` can represent either a single result or multiple results. `response.body.kind` is either `'single'` or `'incremental'`. If it is `'single'`, then incremental delivery has not been used, and `response.body.singleResult` is an object with `data`, `errors`, and `extensions` fields. If it is `'incremental'`, then `response.body.initialResult` is the initial result of the operation, and `response.body.subsequentResults` is an async iterator that will yield subsequent results. (The precise structure of `initialResult` and `subsequentResults` is defined by `graphql-js` and may change between the current pre-release of `graphql-js` v17 and its final release; if you write code that processes these values before `graphql-js` v17 has been released you may have to adapt it when the API is finalized. Apollo Server currently only supports `17.0.0-alpha.2`, not newer alphas which use a different format.)

The `http` field contains an optional numeric `status` code and a `headers` map specifying any HTTP status code and headers that should be set.

Below are the available fields for the first argument of `executeOperation`:

### Fields

<table class="field-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Description</th>
    </tr>
  </thead>

<tbody>
<tr class="required">
<td>

###### `query`

`string` or `DocumentNode`

</td>

<td>

**Required**. The GraphQL operation to run. Note that you must use the `query` field even if the operation is a mutation. This may also be a [`TypedQueryDocumentNode`](https://github.com/graphql/graphql-js/blob/main/src/utilities/typedQueryDocumentNode.ts), in which case TypeScript types for the `variables` option and `response.body.singleResult.data` will be automatically inferred.

</td>
</tr>

<tr>
<td>

###### `variables`

`object`

</td>
<td>
An object containing any GraphQL variables to use as argument values for the executed operation.
</td>
</tr>

<tr>
<td>

###### `operationName`

`string`

</td>
<td>

If `query` contains more than one operation definition, you must provide this option to indicate which operation to execute.

</td>
</tr>

<tr>
<td>

###### `extensions`

`object`

</td>
<td>

The `extensions` object is usually used to pass request metadata within your server from one touch point to another (e.g., from a request to a plugin) during the lifecycle of a request. In this scenario, this object represents the request extensions sent in an actual request.

</td>
</tr>

<tr>
<td>

###### `http`

`HTTPGraphQLRequest`

</td>
<td>

An object implementing the [`HTTPGraphQLRequest`](https://github.com/apollographql/apollo-server/blob/2d5d564abe3d817f8902f07a712a6e105f1b2e41/packages/server/src/externalTypes/http.ts#L2) interface, containing information that pertains to the incoming HTTP request.

</td>
</tr>

</tbody>
</table>


## `executeHTTPGraphQLRequest`

The `executeHTTPGraphQLRequest` method is the main entry point for web framework integrations. You can pass a [`HTTPGraphQLRequest`](../integrations/building-integrations/#construct-the-httpgraphqlrequest-object) object to the `executeHTTPGraphQLRequest` method to execute a GraphQL request:

<MultiCodeBlock>

```ts
const result = await server.executeHTTPGraphQLRequest({
  httpGraphQLRequest: OurHttpGraphQLRequest,
  context: async () => ({
    // token: ...,
  }),
});
```

</MultiCodeBlock>

For details and examples, see [Building Integrations](../integrations/building-integrations/#execute-the-graphql-request).

## `cache`

A public readonly field on `ApolloServer` that enables you to access your server's [cache](#cache).

## `logger`

A public readonly field on `ApolloServer` that enables you to access your server's [logger](#logger).
